/*
 * Created on 15 avr. 2007
 */
package fr.mywiki.business.wiki.render.filter;

import org.jdom.Element;
import org.radeox.filter.CacheFilter;
import org.radeox.filter.context.FilterContext;
import org.radeox.filter.regex.LocaleRegexTokenFilter;
import org.radeox.filter.regex.RegexTokenFilter;
import org.radeox.regex.MatchResult;

import fr.mywiki.business.wiki.render.WikiRenderEngine;
import fr.mywiki.business.xml.XmlManager;

/**
 * Generic filter for both types of lists : ordered and unordered.
 * 
 * @author Thomas
 */
public abstract class ListFilter extends LocaleRegexTokenFilter implements
		CacheFilter {

	/** Returns the key of this filter */
	protected abstract String getLocaleKey();

	/** Returns a Element object containing the main markup of the list object. */
	public abstract Element getMainElement();
	
	/**
	 * Returns the element in the match regex which begins each line of the list and makes
	 * the difference between all the types.
	 */
	public abstract int getListElementBegin();

	/**
	 * <p>
	 * Method called for every occurence of the regular expression LOCALE_KEY. The
	 * buffer is concatened with html code computed here from the match result.
	 * </p>
	 * 
	 * @param buffer
	 *          Buffer to write replacement string to
	 * @param matchResult
	 *          Hit with the found regular expression
	 * @param context
	 *          FilterContext for filters
	 * 
	 * @see RegexTokenFilter#handleMatch(java.lang.StringBuffer,
	 *      org.radeox.regex.MatchResult, org.radeox.filter.context.FilterContext)
	 */
	public void handleMatch(StringBuffer buffer, MatchResult matchResult,
			FilterContext context) {
		String listPattern = matchResult.group(0);

		Element mainElement = getMainElement();

		String[] lines = listPattern.split(WikiRenderEngine.LINE_DELIM_REGEX);
		for (int i = 0; i < lines.length; i++) {
			String line = lines[i];

			// Count the number of spaces before the star : indicates the level of the
			// element. Cannot be more than 5.
			int pos = line.indexOf(getListElementBegin());
			int level = pos / 2;
			if (level < 1)
				level = 1;
			if (level > 5)
				level = 5;

			String text = line.substring(pos + 1).trim();

			Element li = new Element("li");
			li.addAttribute("class", "level" + level);

			Element div = new Element("div");
			div.addAttribute("class", "li");
			div.setText(text);

			li.addContent(div);
			mainElement.addContent(li);
		}

		buffer.append(XmlManager.XmlToString(mainElement));
	}
}
